/**    
 * @Description:博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author:顶风少年   
 * @date:   2021年4月1日 下午10:55:40
 */
package datang.dtdb.session.defaults;

import datang.dtdb.executor.Executor;
import datang.dtdb.mapping.Environment;
import datang.dtdb.session.Configuration;
import datang.dtdb.session.ExecutorType;
import datang.dtdb.session.SqlSession;
import datang.dtdb.session.SqlSessionFactory;
import datang.dtdb.session.TransactionIsolationLevel;
import datang.dtdb.transaction.Transaction;
import datang.dtdb.transaction.TransactionFactory;

/**
 * 默认的SqlSession工厂
 */
public class DefaultSqlSessionFactory implements SqlSessionFactory {

	/**
	 * 全局配置类
	 */
	public Configuration configuration;

	/**
	 * 接收Configuration
	 */
	public DefaultSqlSessionFactory(Configuration configuration) {
		this.configuration = configuration;
	}

	/**
	 * 获取一个默认的SqlSession
	 */
	public SqlSession openSession() {
		return openSession(false, TransactionIsolationLevel.REPEATABLE_READ);

	}

	@Override
	public SqlSession openSession(Boolean autoCommit) {
		return openSession(autoCommit, TransactionIsolationLevel.REPEATABLE_READ);
	}

	@Override
	public SqlSession openSession(TransactionIsolationLevel level) {
		return openSession(false, level);
	}

	@Override
	public SqlSession openSession(Boolean autoCommit, TransactionIsolationLevel level) {
		return openSessionFromDataSource(configuration.getDefaultExecutorType(), level, autoCommit);
	}

	/**
	 * openSession时可以设置是否自动提交，执行器类型，事务隔离级别还有连接，此处还需要优化
	 */
	private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
			boolean autoCommit) {
		Environment environment = configuration.getEnvironment();
		TransactionFactory transactionFactory = environment.getTransactionFactory();
		Transaction tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
		Executor executor = configuration.newExecutor(tx, execType);
		return new DefaultSqlSession(configuration, executor, autoCommit);
	}

}
